#!/bin/bash
#
# Graphical utility to produce symmetric encryption using openssl's aes-256
# cipher.
# 
# Does not sign the message or produce public-key encryption. You've been
# warned!
#
# Copyright 2016-2017 - Klaus Zimmermann <https://quitter.se/kzimmermann>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

crash() {
    # shorthand function that displays an error message and quits
    # $1 is the message to be displayed.
    echo "Error: $1"
    exit 1
}

encrypt() {
    # encrypts a message using openssl's aes-256-cbc cipher
    # arguments: MESSAGE, KEY
    tmp=$(echo "$1" | openssl aes-256-cbc -a -salt -pass pass:"$2")
    echo "$tmp" | sed "s/$\n//g"
}

decrypt() {
    # decrypts a message encrypted with the encrypt() function
    # arguments: MESSAGE, KEY
    echo "$1" | openssl aes-256-cbc -d -a -salt -pass pass:"$2" || 
        crash "decryption failed."
}

which openssl > /dev/null || crash "OpenSSL not found!"
which zenity > /dev/null || crash "zenity not found!"

while [[ true ]]
do
    form_data=$(zenity --forms \
        --title "Simmetric Encryption Applet" \
        --text="Enter some text to encrypt and the session password" \
        --add-entry="Message" \
        --add-password="Session key" \
        --add-combo="Action:" \
        --combo-values="encrypt|decrypt" \
    ) || exit 0
    text=$(echo "$form_data" | cut -d "|" -f 1)
    key=$(echo "$form_data" | cut -d "|" -f 2)
    action=$(echo "$form_data" | cut -d "|" -f 3)

    case "$action" in
        "encrypt" )
            echo "$(encrypt "$text" "$key")"
            echo "$(encrypt "$text" "$key")" |
            zenity --text-info \
                --width 700 \
                --height 400 \
                --title "Encrypted session message"
        ;;
        "decrypt" )
            echo "$(decrypt "$text" "$key")" |
            zenity --text-info \
                --width 700 \
                --height 400 \
                --title "Decrypted session message"
        ;;
        * )
            echo "Please choose an action from the menu."
        ;;
    esac
done
